<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>子组件向父组件传递数据</title>
  <style>
    #app {
      width: 200px;
      margin: 0 auto;
    }

    button {
      margin: 20px 10px 0 0;
      padding: 10px;
      border: 1px solid steelblue;
      border-radius: 4px;
      font-size: 16px;
      background-color: #ffffff;
    }
  </style>
</head>

<body>

  <!-- 父组件模板 -->
  <div id="app">
    <cpn @item-click="cpnClick"></cpn>
  </div>

  <!-- 子组件模板 -->
  <template id="cpn">
    <div class="border">
      <button v-for="(item, index) in categories" @click="btnClick(item)">{{ item.name }}</button>
    </div>
  </template>

  <script src="../../js/vue.js"></script>
  <script>
    // 创建子组件
    const cpn = {
      template: '#cpn',
      data() {
        return {
          categories: [
            { id: '1', name: '热门推荐' },
            { id: '2', name: '电脑办公' },
            { id: '3', name: '家用电器' },
            { id: '4', name: '智能家居' },
          ]
        }
      },

      methods: {
        btnClick(item) {
          this.$emit('item-click', item);
        }
      }
    }

    // 父组件，内部注册子组件
    const app = new Vue({
      el: '#app',
      data: {},

      components: {
        cpn
      },

      methods: {
        cpnClick(item) {
          console.log("我这边已经收到子组件自定义事件消息", item);
        }
      }
    })
  </script>
</body>

</html>